# -*- coding: utf-8 -*-


from keras.callbacks import ModelCheckpoint
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.layers.core import Dense, Dropout, Activation, Flatten
# from __future__ import absolute_import
# from __future__ import print_function
from keras.models import Sequential
from keras.optimizers import SGD
import os

class Vector2CByNN:
    model = None

    wordvector_dim = 200
    max_words_in_sentence = 50

    path_of_model = "output/cnn_sentence_c.model"

    def __init__(self):
        self.model = self.__build_model()

    def __build_model(self):
        model = Sequential()
        #kernel_regularizer=l2(0.001), bias_regularizer=l2(0.001), activity_regularizer=l2(0.001)
        #model.add(Convolution2D(50, (my_config.max_words_in_sentence, 1), padding='same',input_shape=(my_config.max_words_in_sentence, my_config.wordvector_dim, 1)))
        model.add(Convolution2D(100, (1, self.wordvector_dim), padding='same',input_shape=(self.max_words_in_sentence, self.wordvector_dim, 1)))
        model.add(Activation('relu'))
        #model.add(MaxPooling2D(pool_size=(2, 2)))
        #model.add(Dropout(0.25))

        #model.add(Convolution2D(50*2, (5, 5), padding='same'))
        #model.add(Activation('relu'))
        #model.add(MaxPooling2D(pool_size=(2, 2)))
        #model.add(Dropout(0.25))

        #model.add(Convolution2D(50, (50, 1), padding='same'))
        #model.add(Activation('relu'))

        model.add(MaxPooling2D(pool_size=(2, 2)))
        #model.add(MaxPooling1D(pool_size=2))
        #model.add(Flatten())
        #model.add(Dense(512, kernel_initializer='normal'))
        #model.add(Activation('tanh'))
        model.add(Flatten())
        model.add(Dense(6, kernel_initializer='normal'))
        model.add(Dropout(0.25))
        model.add(Activation('softmax'))

        sgd = SGD(lr=0.0065, decay=1e-6, momentum=0.9, nesterov=True)
        model.compile(loss='categorical_crossentropy', optimizer=sgd,class_mode="categorical",metrics=['accuracy'])

        return model

    def save(self,path="output/cnn_sentence_c.model.final"):
        self.path_of_model = path
        self.model.save_weights(path)

    def load(self,path="output/cnn_sentence_c.model.final"):
        self.path_of_model = path
        if os.path.exists(path):
            self.model.load_weights(path)


    def train(self,data,label):
        checkpointer = ModelCheckpoint(filepath=self.path_of_model,verbose=1,save_best_only=True)
        #model.fit(data, label, batch_size=100,nb_epoch=10,shuffle=True,verbose=1,show_accuracy=True,validation_split=0.2,callbacks=[checkpointer])
        result = self.model.fit(data, label, batch_size=100,epochs=10,shuffle=True,verbose=1,validation_split=0.2,callbacks=[checkpointer])
        return result


    def predict(self, X):
        Y = self.model.predict(X)
        return Y


if __name__ == "__main__":
    m = Vector2CByNN()